package com.chisheng.caa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chisheng.caa.config.RedisCacheNames;
import com.chisheng.caa.exception.DuplicateLoginException;
import com.chisheng.caa.mapper.UserMapper;
import com.chisheng.caa.pojo.LoginUserDetails;
import com.chisheng.caa.pojo.entity.User;
import com.chisheng.caa.util.RedisCacheUtil;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<>();
        userQuery.eq(User::getUsername, username);
        User user = userMapper.selectOne(userQuery);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        String key = RedisCacheNames.OAUTH_PREFIX + user.getUserId();
        if (redisCacheUtil.getCacheObject(key) != null) {
            throw new DuplicateLoginException("重复登录系统");
        }
        return new LoginUserDetails(user, List.of());
    }

}
